#include "message.h"
#include "myLog.h"
#include "utility.h"
#include <iostream>
#include <string>
#include <list>
#include <sstream>
#include <map>

message::message(){};
message::~message(){};

map<int,string> message::mapSystemMessages;
long message::longMessageLastModify = 0;

void message::LoadSystemMessage()
{
    char txt[1024];
    std::ifstream inFile;

    inFile.open("message.ini");
    if (!inFile) {
        string strmsg = "Unable to open message file [ message.ini ]";
        myLog m = myLog("message");
        m.writelog(strmsg.c_str());
        cout << strmsg << endl;
    }
    string strKey, strValue;
    int msgnum;
    while(!inFile.eof())
    {
        inFile.getline(txt,1024,'\n');
        utility::splistString(txt, '=', &strKey, &strValue);
        msgnum = utility::string2int(strKey);
        char chrPrefix = strKey.c_str()[0];
        if (chrPrefix != '#')
		{
	        if (strKey != "" && strValue != "") mapSystemMessages[msgnum] = strValue;
		}
    }
    inFile.close();
}

std::string message::GetNormalMessage(int x)
{
	//Check if file has been update or first get message, reload file.
	long longLastTime = rfile::getFileLastModifyDateTime("message.ini");
	if ((message::longMessageLastModify == 0) || (message::longMessageLastModify != longLastTime))
	{
		message::longMessageLastModify = longLastTime;
		message::LoadSystemMessage();
	}
    map<int,string>::iterator it;
    it=mapSystemMessages.find(x);
    if (it != mapSystemMessages.end())
    {
        return it->second;
    }else{
        return "Using undefined message in message.ini file.";
    }
}
